import MessageComponent from './Message.vue';
import {createApp, ComponentPublicInstance, App} from 'vue';
import {useOverlay} from "../../uses/overlay";
import mitt, {Emitter} from 'mitt';
type theme = 'info' | 'success' | 'warning' | 'error';
export interface MessageOptions {
  type: theme;
  duration: number;
  pauseOnHover: boolean;
  animate: boolean;
}

export interface MessageItemData {
  messageId: string;
  content: string;
  onClose: Emitter;
  show: boolean;
  options: MessageOptions;
}

interface MessageContainerInstance extends ComponentPublicInstance {
  createMessage(options: MessageItemData): void;
  emitter: Emitter;
}

let _id = 0;

export class MessageService {
  private message: MessageContainerInstance | undefined;
  private overlay: HTMLElement | undefined;
  private defOptions: MessageOptions;
  readonly emitter: Emitter;
  constructor(options?: Partial<MessageOptions>) {
    this.emitter = mitt();
    this.defOptions = {
      type: 'info',
      duration: 1500,
      pauseOnHover: true,
      animate: true,
      ...options
    }
  }

  create(content: string, options?: Partial<MessageOptions>) {
    if (!this.message) {
      this.message = this.getMessage();
    }
    const trueOptions: MessageOptions = {
      ...this.defOptions,
      ...options
    }
    const messageData = {
      messageId: 'message-' + _id++,
      content,
      show: true,
      options: trueOptions,
      onClose: mitt()
    };
    this.message.createMessage(messageData);
    return messageData;
  }

  private getMessage(): MessageContainerInstance {
    this.overlay = useOverlay({ pointerEvents: 'none' })!.overlay;
    const message = createApp(MessageComponent).mount(this.overlay) as MessageContainerInstance;
    // console.log('message ins', message);
    message.emitter.on('clear', () => {
      console.log('onClear');
      this.overlay?.remove();
      _id = 0;
      this.message = undefined;
    });
    return message;
  }
}

export interface MessagePluginOptions extends MessageOptions {
  key: string;
}

export default function (app: App, options?: MessagePluginOptions) {
  const message = new MessageService(options);
  app.provide<MessageService>(options?.key || 'messageKey', message);
}
